<!-- 富文本编辑器 -->
<template>
  <div class="quill">
    <quill-editor
      v-bind="$attrs"
      v-on="$listeners"
      :value="value"
      ref="myQuillEditor"
      class="myQuillEditor"
      :options="editorOption"
    ></quill-editor>
    <!-- 使用input 标签劫持原本视频上传事件，实现视频上传 -->
    <input
      type="file"
      accept="video/*"
      name="file"
      ref="uploadFileVideo"
      id="uploadFileVideo"
      @change="changevideo"
      style="opacity: 0; width: 0; height: 0; cursor: pointer"
    />
    <!-- <input
      type="file"
      accept="image/*"
      name="file"
      ref="uploadFileImage"
      id="uploadFileImage"
      @change="changeimage"
      style="opacity: 0; width: 0; height: 0; cursor: pointer"
    /> -->
  </div>
</template>

<script>
import { upload } from "@/api/upload";
import { quillEditor, Quill } from "vue-quill-editor";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import VideoBlot from "./video.js";
import { container, ImageExtend, QuillWatch } from "quill-image-extend-module";
import ImageResize from "quill-image-resize-module";
Quill.register(VideoBlot);
Quill.register("modules/ImageExtend", ImageExtend);
Quill.register("modules/ImageResize", ImageResize);

export default {
  name: "",
  components: {
    quillEditor,
  },
  props: { value: "" },
  data() {
    return {
      result: this.value,
      editorOption: {
        placeholder: "输入文本...",
        modules: {
          ImageResize: {
            displayStyles: {
              backgroundColor: "black",
              border: "none",
              color: "white",
            },
            modules: ["Resize", "DisplaySize", "Toolbar"],
          },
          ImageExtend: {
            // 如果不作设置，即{}  则依然开启复制粘贴功能且以base64插入
            name: "file", // 图片参数名
            size: 3, // 可选参数 图片大小，单位为M，1M = 1024kb
            action: "http://localhost:5000/upload", // 服务器地址, 如果action为空，则采用base64插入图片
            // response 为一个函数用来获取服务器返回的具体图片地址
            response: (res) => {
              //回调中调用  this.insertEle('image', data); 方法，插入图片到富文本
              this.insertEle("image", "http://localhost:5000" + res.path);
            },
            headers: (xhr) => {
              // xhr.setRequestHeader('Content-Type','multipart/form-data')
            }, // 可选参数 设置请求头部
            sizeError: () => {}, // 图片超过大小的回调
            start: () => {}, // 可选参数 自定义开始上传触发事件
            end: () => {}, // 可选参数 自定义上传结束触发的事件，无论成功或者失败
            error: () => {}, // 可选参数 上传失败触发的事件
            success: () => {}, // 可选参数  上传成功触发的事件
            change: (xhr, formData) => {
              // xhr.setRequestHeader('myHeader','myValue')
              // formData.append('token', 'myToken')
            }, // 可选参数 每次选择图片触发，也可用来设置头部，但比headers多了一个参数，可设置formData
          },
          toolbar: {
            container: [
              ["bold", "italic", "underline", "strike"], //加粗，斜体，下划线，删除线
              ["blockquote", "code-block"], //引用，代码块
              [{ header: 1 }, { header: 2 }], // 标题，键值对的形式；1、2表示字体大小
              [{ list: "ordered" }, { list: "bullet" }], //列表
              [{ script: "sub" }, { script: "super" }], // 上下标
              [{ indent: "-1" }, { indent: "+1" }], // 缩进
              [{ direction: "rtl" }], // 文本方向
              [
                {
                  size: ["small", false, "large", "huge"],
                },
              ], // 字体大小，false设置自定义大小
              [{ header: [1, 2, 3, 4, 5, 6, false] }], //几级标题
              [{ color: [] }, { background: [] }], // 字体颜色，字体背景颜色
              [{ align: [] }], //对齐方式
              ["clean"], //清除字体样式
              ["image", "video"], //上传图片、上传视频
            ],
            handlers: {
              // 拦截默认选择视频事件
              video: function (val) {
                // 劫持原来的视频点击按钮事件
                document.querySelector("#uploadFileVideo").click();
              },
              // 拦截默认选择图片事件
              // image: function (val) {
              //   document.querySelector("#uploadFileImage").click();
              // },
              // 插件上传图片
              image: function () {
                QuillWatch.emit(this.quill.id);
              },
            },
          },
        },
      },
      // toolbar标题
      titleConfig: [
        { Choice: ".ql-insertMetric", title: "跳转配置" },
        { Choice: ".ql-bold", title: "加粗" },
        { Choice: ".ql-italic", title: "斜体" },
        { Choice: ".ql-underline", title: "下划线" },
        { Choice: ".ql-header", title: "段落格式" },
        { Choice: ".ql-strike", title: "删除线" },
        { Choice: ".ql-blockquote", title: "块引用" },
        { Choice: ".ql-code", title: "插入代码" },
        { Choice: ".ql-code-block", title: "插入代码段" },
        { Choice: ".ql-font", title: "字体" },
        { Choice: ".ql-size", title: "字体大小" },
        { Choice: '.ql-list[value="ordered"]', title: "编号列表" },
        { Choice: '.ql-list[value="bullet"]', title: "项目列表" },
        { Choice: ".ql-direction", title: "文本方向" },
        { Choice: '.ql-header[value="1"]', title: "h1" },
        { Choice: '.ql-header[value="2"]', title: "h2" },
        { Choice: ".ql-align", title: "对齐方式" },
        { Choice: ".ql-color", title: "字体颜色" },
        { Choice: ".ql-background", title: "背景颜色" },
        { Choice: ".ql-image", title: "图像" },
        { Choice: ".ql-video", title: "视频" },
        { Choice: ".ql-link", title: "添加链接" },
        { Choice: ".ql-formula", title: "插入公式" },
        { Choice: ".ql-clean", title: "清除字体格式" },
        { Choice: '.ql-script[value="sub"]', title: "下标" },
        { Choice: '.ql-script[value="super"]', title: "上标" },
        { Choice: '.ql-indent[value="-1"]', title: "向左缩进" },
        { Choice: '.ql-indent[value="+1"]', title: "向右缩进" },
        { Choice: ".ql-header .ql-picker-label", title: "标题大小" },
        {
          Choice: '.ql-header .ql-picker-item[data-value="1"]',
          title: "标题一",
        },
        {
          Choice: '.ql-header .ql-picker-item[data-value="2"]',
          title: "标题二",
        },
        {
          Choice: '.ql-header .ql-picker-item[data-value="3"]',
          title: "标题三",
        },
        {
          Choice: '.ql-header .ql-picker-item[data-value="4"]',
          title: "标题四",
        },
        {
          Choice: '.ql-header .ql-picker-item[data-value="5"]',
          title: "标题五",
        },
        {
          Choice: '.ql-header .ql-picker-item[data-value="6"]',
          title: "标题六",
        },
        { Choice: ".ql-header .ql-picker-item:last-child", title: "标准" },
        {
          Choice: '.ql-size .ql-picker-item[data-value="small"]',
          title: "小号",
        },
        {
          Choice: '.ql-size .ql-picker-item[data-value="large"]',
          title: "大号",
        },
        {
          Choice: '.ql-size .ql-picker-item[data-value="huge"]',
          title: "超大号",
        },
        { Choice: ".ql-size .ql-picker-item:nth-child(2)", title: "标准" },
        { Choice: ".ql-align .ql-picker-item:first-child", title: "居左对齐" },
        {
          Choice: '.ql-align .ql-picker-item[data-value="center"]',
          title: "居中对齐",
        },
        {
          Choice: '.ql-align .ql-picker-item[data-value="right"]',
          title: "居右对齐",
        },
        {
          Choice: '.ql-align .ql-picker-item[data-value="justify"]',
          title: "两端对齐",
        },
      ],
    };
  },
  methods: {
    // 标题中文注释
    initTitle() {
      document.getElementsByClassName("ql-editor")[0].dataset.placeholder = "";
      for (let item of this.titleConfig) {
        let tip = document.querySelector(".quill-editor " + item.Choice);
        if (!tip) continue;
        tip.setAttribute("title", item.title);
      }
    },
    //上传图片到服务器
    // async changeimage(file) {
    //   console.log("上传图片");
    //   var formData = new FormData();
    //   formData.append("file", file.target.files[0]);
    //   const res = await upload(formData);
    //   console.log(res);
    //   if (res.code == 200) {
    //     //回调中调用  this.insertEle('image', data); 方法，插入图片到富文本
    //     this.insertImg("image", "http://localhost:5000" + res.path);
    //   }
    // },
    //上传视频到服务器
    async changevideo(file) {
      var formData = new FormData();
      formData.append("file", file.target.files[0]);
      const res = await upload(formData);
      console.log(res);
      if (res.code == 200) {
        //回调中调用  this.insertEle('video', data); 方法，插入视频到富文本
        this.insertEle("video", "http://localhost:5000" +res.path);
      }
    },
    // 上传完成后调用
    insertEle(type, url) {
      let quill = this.$refs.myQuillEditor.quill;
      let length = quill.getSelection().index;
      // 插入视频  url为服务器返回的图片地址
      if (type === "image") {
        quill.insertEmbed(length, "image", url);
      } else {
        quill.insertEmbed(length, "simpleVideo", {
          url,
          width: "100%",
          height: "auto",
          controls: "controls",
        });
      }
      // 调整光标到最后
      quill.setSelection(length + 1);
    },
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {
    this.initTitle();
  },
};
</script>

<style lang="scss" scoped>
.quill {
  width: 1100px;
  height: 600px;
  display: flex;
  flex-direction: column;
  background-color: #fff;

  #Quill {
    flex: 1;
    width: 100%;
    overflow-y: auto;
  }
}
</style>
